const md5 = require('md5')
const base64 = require('base64')
const config = require('../config')
/**
 * 格式化时间对象
 * date: 时间戳
 * Symbol:数字之间是否需要符号
 */
function formatTime(date, Symbol = true) {
    date = new Date(date)
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    if (Symbol) {
        return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
    } else {
        return [year, month, day, hour, minute, second].map(formatNumber).join('')
    }
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function timestamptostr(timestamp) {
    var Hours = parseInt(timestamp / 3600),
        Remainingm = timestamp % 3600,
        Minutes = parseInt(Remainingm / 60),
        Seconds = Remainingm % 60
    if (Minutes < 10) {
        Minutes = '0' + Minutes
    }
    if (Seconds < 10) {
        Seconds = '0' + Seconds
    }
    return Hours + ':' + Minutes + ':' + Seconds
}

/**
 * 可逆加密
 * @param  string data 需要加密的数据
 * @param  string key  密码
 * @return string       加密后的数据
 */
function mwencrypt(data, key = 'xfz61281006') {
    key = md5.hex_md5(key)
    var x = 0,
        len = data.length,
        l = key.length,
        char = '',
        str = ''
    for (var i = 0; i < len; i++) {
        if (x == l) {
            x = 0
        }
        char += key.substring(x, x + 1)
        x++
    }
    for (var i = 0; i < len; i++) {
        str += String.fromCharCode((data.substring(i, i + 1).charCodeAt()) + ((char.substring(i, i + 1)).charCodeAt()) % 256)
    }
    return base64.base64encode(str)
}
/**
 * 解密
 * @param  string $data 需要解密的数据
 * @param  string $key  密码
 * @return string       解密后的数据
 */
function mwdecrypt(data, key = 'xfz61281006') {
    key = md5.hex_md5(key)
    var x = 0,
        data = base64.base64decode(data),
        len = data.length,
        l = key.length,
        char = '',
        str = ''
    for (var i = 0; i < len; i++) {
        if (x == l) {
            x = 0
        }
        char += key.substr(x, 1)
        x++
    }
    for (var i = 0; i < len; i++) {
        if ((data.substr(i, 1)).charCodeAt() < (char.substr(i, 1)).charCodeAt()) {
            str += String.fromCharCode(((data.substr(i, 1)) + 256).charCodeAt() - (char.substr(i, 1)).charCodeAt())
        }
        else {
            str += String.fromCharCode((data.substr(i, 1).charCodeAt()) - (char.substr(i, 1)).charCodeAt())
        }
    }
    return str
}
/**
 * 将数字转换为时间（如：2300转为结果为23：00）
 */
function numtotime(num) {
    var str = num.toString()
    var startstr = str.substr(0, str.length - 2)
    var endstr = str.substr(-2)
    if (!startstr) {
        startstr = '00'
    } else if (startstr < 10) {
        startstr = '0' + startstr
    }
    if (endstr == 0) {
        endstr = '00'
    }
    return startstr + ':' + endstr;
}
/**
 * 
 */
function timetonum(str) {
    var startstr = str.substr(0, str.length - 3)
    var endstr = str.substr(-2)
    return parseInt(startstr + endstr)
}
/**
 * 生成header key
 */
function createheaderkey() {
    var timestamp = Date.parse(new Date()) / 1000
    var key = md5.hex_md5(config.headerkey + timestamp)
    var resource = {
        'timestamp': timestamp,
        'key': key
    }
    return resource
}
/**
 * 生成随机字符串
 * len: 字符串长度
 */
function RandomString(len) {
  len = len || 32;
  //var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
  var maxPos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

module.exports = {
    mwencrypt: mwencrypt,
    mwdecrypt: mwdecrypt,
    numtotime: numtotime,
    timetonum: timetonum,
    createheaderkey: createheaderkey,
    timestamptostr: timestamptostr,
    formatTime: formatTime,
    RandomString: RandomString

}
